/*Elise Eiden
Taryn Green
Kevin McGinn 

Software Engineering
Network Feasibility Test

Referencing the Boost Daytime example

A simple server. It holds the coordinates of the center of a cube and receives input from a client to update the coordinates. It then returns the cube in a message.*/


#include <ctime>
#include <iostream>
#include <string>
#include <boost/array.hpp>
#include <boost/asio.hpp>

using boost::asio::ip::udp;

///This portion is modified from the reference
//Initialize cube 
//Later to be a cube object
int cube_x = 0;
int cube_y = 0;
int cube_z = 0;
///

/*std::string make_daytime_string()
{
  using namespace std; // For time_t, time and ctime;
  time_t now = time(0);
  return ctime(&now);
}*/

///This portion is modified from the reference
std::string make_cube_string()
{
	char buf[33];
      //make the message to send
      std::string cube_position;
      //note: this is a temporary fix until we make a cube class
      //with a serialize function
      cube_position.append("x: ");
	snprintf(buf, sizeof(buf), "%d", cube_x);
	cube_position.append(buf);
      cube_position.append("\ty: ");
	snprintf(buf, sizeof(buf), "%d", cube_y);
	cube_position.append(buf);
      cube_position.append("\tz: ");
	snprintf(buf, sizeof(buf), "%d", cube_z);
	cube_position.append(buf);
	cube_position.append("\n");
return cube_position;
}
///

int main()
{
  try
  {
    boost::asio::io_service io_service;

    udp::socket socket(io_service, udp::endpoint(udp::v4(), 13));

    //Listen for messages from client
    for (;;)
    {
      boost::array<char, 1> recv_buf;
      udp::endpoint remote_endpoint;
      boost::system::error_code error;

      //Receive buffer
      socket.receive_from(boost::asio::buffer(recv_buf),
          remote_endpoint, 0, error);

	///This portion is modified from the reference
	std::cout<< "Received: " << recv_buf[0] << std::endl;

	//Update buffer
	switch(recv_buf[0]) {
	case 'a':
		cube_x--;
		break;
	case 'd':
		cube_x++;
		break;
	case 's':
		cube_y--;
		break;
	case 'w':
		cube_y++;
		break;
	case 'q':
		cube_z--;
		break;
	case 'e':
		cube_z++;
		break;
	}
	///

      if (error && error != boost::asio::error::message_size)
        throw boost::system::system_error(error);

	//      std::string message = make_daytime_string();
      std::string message = make_cube_string();			//Make string from cube coordinates
      boost::system::error_code ignored_error;
      //Return cube string
      socket.send_to(boost::asio::buffer(message),	
          remote_endpoint, 0, ignored_error);
    }
  }
  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}
